
package com.tools.cleanmaster.manager;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlarmManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.text.TextUtils;

import com.tools.cleanmaster.candysaver.CandySaverNotification;
import com.tools.cleanmaster.scenenew.BatteryInfoTracker;
import com.tools.cleanmaster.store.CandySaverSharedPrefManager;
import com.tools.cleanmaster.store.GlobalSharedPrefManager;
import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.LogHelper;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class CandySaverManager implements BatteryInfoTracker.BatteryInfoListener {

    private static final String TAG = "LockScreenManager";

    // 屏保引导功能电量阈值
    private static final int LOCKSCREEN_GUIDE_BATTERY_PERCENT = 89;

    private static CandySaverManager sManager;
    private Context mAppContext;
    private AtomicBoolean mRegisterFlag = new AtomicBoolean(false);
    private BroadcastReceiver mReceiver;

    private CandySaverManager(Context appCtx) {
        mAppContext = appCtx.getApplicationContext();
    }

    public static CandySaverManager getInstance(Context ctx) {
        if (sManager == null) {
            synchronized (CandySaverManager.class) {
                if (sManager == null) {
                    sManager = new CandySaverManager(ctx.getApplicationContext());
                }
            }
        }
        return sManager;
    }

    public void start() {
        boolean registered = mRegisterFlag.getAndSet(true);
        if (registered) {
            return;
        }

        // 注册电量监听
        BatteryInfoTracker.getInsance(mAppContext).registerListener(this);

        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_ON.equals(action)) {
                    BatteryInfoTracker.BatteryInfo data = BatteryInfoTracker.getInsance(context).getBatteryData();
                    onBatteryInfoUpdated(data);
                }
            }
        };

        // 注册屏幕打开监听
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        try {
            mAppContext.registerReceiver(mReceiver, filter);
        } catch (Throwable e) {
            if (FeatureConfig.DEBUG_LOG) {
                e.printStackTrace();
            }
        }

        CandySaverSharedPrefManager.getInstance(mAppContext).registerDataPipe();
    }

    public void stop() {
        boolean registered = mRegisterFlag.getAndSet(false);
        if (!registered) {
            return;
        }

        BatteryInfoTracker.getInsance(mAppContext).unregisterListener(this);

        try {
            mAppContext.unregisterReceiver(mReceiver);
        } catch (Throwable e) {
            if (FeatureConfig.DEBUG_LOG) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onBatteryInfoUpdated(BatteryInfoTracker.BatteryInfo newData) {
        // 没有出于充电状态，不做处理
        if (newData == null || newData.plugType == 0) {
            return;
        }
        // 电量百分比有错，不做处理
        if (newData.percent < 0 || newData.percent > 100) {
            return;
        }

        /*
         * 关闭电量变化时打开充电屏保的功能 // 在Api21(android //
         * 5.0)上PackageUtils.isHome方法失效,由于无法判断当前应用是否是桌面应用,所以产品决定在此问题上面插拔充电器不弹出屏保(5.1统一修改) if
         * (Build.VERSION.SDK_INT >= 21) { return; } // 即使满电，插上电源也照样出现屏保 if
         * (ChargingConfigs.getInstance(imContext).isScreenSaverOpen() && BService.isInHome() &&
         * !AccessibilityLoadingWindow.getsInstance().isWindowRunning()) {
         * ChargingLockScreenHelper.tryShowLockScreen(imContext); }
         */
        if (newData.percent <= LOCKSCREEN_GUIDE_BATTERY_PERCENT && readyShow()) {
            show();
        }
    }

    private boolean readyShow() {
        // 1. 屏保引导开关为关，不展示
        if (!CandySaverSharedPrefManager.getInstance(mAppContext).getRecommendSwitch()) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.d(TAG, "屏保引导开关为关，不展示");
            }
            return false;
        }
        // 2. 处于新用户保护时间，不展示
        long now = System.currentTimeMillis();

        long firstInstall = GlobalSharedPrefManager.getFirstActiveTime(mAppContext);
        long newProtectTime = CandySaverSharedPrefManager.getInstance(mAppContext).getRecommendNewProTime();

        // 3. 展示次数超过展示上限，不展示
        int hasShowTimes = CandySaverSharedPrefManager.getInstance(mAppContext).getRecommendHasShowTimes();
        int recommendTimes = CandySaverSharedPrefManager.getInstance(mAppContext).getRecommendTimes();
        if (hasShowTimes >= recommendTimes) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.d(TAG, "展示次数超过展示上限，不展示。已展示：" + hasShowTimes + ",上限：" + recommendTimes);
            }
            return false;
        }
        // 4. 上次展示到现在没有达到展示时间间隔，不展示
        long showTime = CandySaverSharedPrefManager.getInstance(mAppContext).getRecommendShowNowTime();
        long showGap = CandySaverSharedPrefManager.getInstance(mAppContext).getRecommendIntTime();
        if (showTime <= now && (now - showTime) < showGap) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.d(TAG, "上次展示到现在没有达到展示时间间隔，不展示。时间间隔：" + showGap / AlarmManager.INTERVAL_HOUR);
            }
            return false;
        }
        // 5. 自己开启了充电屏保，不展示
        /*if (MakingManager.getInstance(imContext).isOpen()) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.d(TAG, "自己开启了充电屏保，不展示");
            }
            return false;
        }*/
        // 6. 自己开启过充电屏保，不展示
        if (CandySaverSharedPrefManager.getInstance(mAppContext).getLockScreenOpened()) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.d(TAG, "自己开启过充电屏保，不展示");
            }
            return false;
        }
        // 7. 判断有没有self版本的充电屏保开启
        /*if (MakingManager.getInstance(imContext).isPrivateOpen()) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.d(TAG, "已经有self版本的充电屏保开启，不展示");
            }
            return false;
        }*/
        // 8. 判断有没有self版本的充电屏保开启过
        /*if (MakingManager.getInstance(imContext).isPrivateHasOpen()) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.d(TAG, "self版本的充电屏保开启过,不展示");
            }
            return false;
        }*/
        // 9. Battery弹出过引导开启充电屏保的dialog，不展示
        /*if (CandySaverSharedPrefManager.getInstance(mAppContext).getBatteryLockScreenGuideShow()) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.d(TAG, "Battery弹出过引导开启充电屏保的dialog，不展示");
            }
            return false;
        }*/
        // 10. Booster弹出过引导开启充电屏保的dialog，不展示
        /*if (CandySaverSharedPrefManager.getInstance(mAppContext).getBoosterLockScreenGuideShow()) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.d(TAG, "Booster弹出过引导开启充电屏保的dialog，不展示");
            }
            return false;
        }*/

        return true;
    }

    public static boolean isHigherAndroid_L() {
        return Build.VERSION.SDK_INT > 21;
    }

    /**
     * SDK>21 展示Notification SDK<=21 展示Dialog
     */
    private void show() {
        if (isHigherAndroid_L()) {
            // 展示充电屏保推荐Notification
            CandySaverNotification.show(mAppContext);
        } else if (atHome(mAppContext)) {
            //BaseFragmentActivity.startBaseFragmentActivity(mAppContext, CandySaverFragment.class.getName());
        } else {
            return;
        }
        int showTime = CandySaverSharedPrefManager.getInstance(mAppContext).getRecommendHasShowTimes() + 1;
        CandySaverSharedPrefManager.getInstance(mAppContext).setRecommendHasShowTimes(showTime);
        CandySaverSharedPrefManager.getInstance(mAppContext).setRecommendShowNowTime(System.currentTimeMillis());
    }

    private static boolean atHome(Context ctx) {

        ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (tasks == null || tasks.isEmpty() || tasks.get(0) == null) {
            return false;
        }
        ComponentName topActivity = tasks.get(0).topActivity;
        if (topActivity == null) {
            return false;
        }
        if (TextUtils.equals(ctx.getPackageName(), topActivity.getPackageName())) {
            return false;
        }

        PackageManager pm = ctx.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        List<ResolveInfo> resolves = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        if (resolves == null || resolves.isEmpty()) {
            return false;
        }
        for (ResolveInfo item : resolves) {
            ComponentName name = new ComponentName(item.activityInfo.packageName, item.activityInfo.name);
            if (name.equals(topActivity)) {
                return true;
            }
        }
        return false;
    }
}
